package com.dwjm.shop.car;

import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/cart")
public class ShopCarHandler extends HttpServlet {
    private ShopCarDao cartDao = new ShopCarDaoImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        // 获取操作类型参数
        String action = req.getParameter("action");

        // 添加商品到购物车
        if("add".equals(action)) {
            handleAddToCart(req, resp);
        }
        // 删除购物车项
        else if("remove".equals(action)) {
            handleRemoveCartItem(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        // 获取用户ID（需要登录验证）
        Long cid = Long.parseLong(req.getParameter("cid"));

        List<ShopCar> cartList = cartDao.getCartList(cid);
        String json = new Gson().toJson(cartList);
        resp.getWriter().write(json);
    }

    private void handleAddToCart(HttpServletRequest req, HttpServletResponse resp)
            throws IOException
    {
        try {
            ShopCar cartItem = new ShopCar();
            cartItem.setGid(Long.parseLong(req.getParameter("gid")));
            cartItem.setTitle(req.getParameter("title"));
            cartItem.setPrice(Double.parseDouble(req.getParameter("price")));
            cartItem.setCid(Long.parseLong(req.getParameter("cid")));

            boolean result = cartDao.addToCart(cartItem);
            resp.getWriter().write(result ? "Y" : "N");
        } catch (NumberFormatException e) {
            resp.getWriter().write("参数错误");
        }
    }

    private void handleRemoveCartItem(HttpServletRequest req, HttpServletResponse resp)
            throws IOException
    {
        try {
            Long itemId = Long.parseLong(req.getParameter("id"));
            boolean result = cartDao.removeCartItem(itemId);
            resp.getWriter().write(result ? "Y" : "N");
        } catch (NumberFormatException e) {
            resp.getWriter().write("参数错误");
        }
    }

}
